const { NAME_OR_PASSWORD_IS_REQURIED, NAME_IS_NOT_EXISTS, PASSWORD_IS_INCORRENT, UNAUTHORIZATION } = require("../config/error-constants");
const { findUserByName } = require("../service/user.service");
const md5Password = require("../utils/md5-password");
const jwt = require('jsonwebtoken');
const { PUBLIC_KEY } = require('../config/secret');

const verifyLogin = async (ctx, next) => {
    const { name, password } = ctx.request.body;
    // console.log(name, password);
    // 1. 判断用户名和密码是否为空
    if (!name || !password) {
        return ctx.app.emit('error', NAME_OR_PASSWORD_IS_REQURIED, ctx)
    }
    // 2. 判断用户名是否存在 在数据库
    const users = await findUserByName(name)
    const user = users[0];
    if (!user) {
        return ctx.app.emit('error', NAME_IS_NOT_EXISTS, ctx)
    }
    // 3. 查询数据库中的密码和用户传递过来的密码是否一致
    if (user.password !== md5Password(password)) {
        return ctx.app.emit('error', PASSWORD_IS_INCORRENT, ctx)
    }
    // 4. 将user信息放在ctx上
    ctx.user = user
    // 4. 密码一致，next进入控制器 颁发令牌，给客户端传回token

    await next()
}
const verifyAuth = async (ctx, next) => {
    // 1. 获取token
    // console.log(ctx.headers.authorization);
    const authorization = ctx.headers.authorization;
    if (!authorization) {
        return ctx.app.emit('error', UNAUTHORIZATION, ctx);
    }
    const token = authorization.replace('Bearer ', '')

    // 2. 验证token

    try {
        const result = jwt.verify(token, PUBLIC_KEY, {
            algorithm: ['RS256'],
        })
        // console.log(result);
        // 将token信息保留下来
        ctx.user = result
        // 执行下一个中间件
        await next();
    } catch (error) {
        // console.log(error);
        ctx.app.emit('error', UNAUTHORIZATION, ctx)
    }

}
module.exports = {
    verifyLogin,
    verifyAuth
}